package com.jjty.dataGenerator.data.service;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jjty.dataGenerator.bg.entity.SchoolInfo;
import com.jjty.dataGenerator.bg.entity.StudentInfo;
import com.jjty.dataGenerator.bg.mapper.SchoolMapper;
import com.jjty.dataGenerator.bg.mapper.StudentInfoMapper;
import com.jjty.dataGenerator.data.entity.*;
import com.jjty.dataGenerator.data.entity.vo.DataTypeConfig;
import com.jjty.dataGenerator.data.entity.vo.GeneratedData;
import com.jjty.dataGenerator.data.mapper.*;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

@Service
public class DataGeneratorService {

    @Resource
    private CallRecordMapper callRecordMapper;
    @Resource
    private XykRecordMapper xykRecordMapper;
    @Resource
    private AttendanceRecordMapper attendanceRecordMapper;
    @Resource
    private TemperatureRecordMapper temperatureRecordMapper;
    @Autowired
    private DataTypeConfigMapper dataTypeConfigMapper;
    @Autowired
    private GeneratedDataMapper generatedDataMapper;
    @Autowired
    private StudentInfoMapper studentInfoMapper;
    @Autowired
    private SchoolMapper schoolMapper;

//    public void callRecordsData(Integer numRecords,String appId,String ecCode,String terminalLocation) {
//        List<ScCallRecord> callRecords = new ArrayList<>();
//        // 从另一个数据库获取 studentId, studentName, studentNumber,phoneNumber 数据
//        List<UserInfo> userInfoList = getUserInfoFromAnotherDatabase(numRecords);
//        for (int i = 0; i < numRecords; i++) {
//            ScCallRecord scCallRecord= new ScCallRecord();
//
////            话机类接口用
//            scCallRecord.setAppId(appId);
//            scCallRecord.setUserType("STUDENT");
//            scCallRecord.setEcCode(ecCode);
//            scCallRecord.setTerminalLocation(terminalLocation);
//            scCallRecord.setAuthenticity("call_records");
////             生成随机时间（最近一天内）
//            LocalDateTime start = LocalDateTime.now().minusDays(1);
//            LocalDateTime end = LocalDateTime.now();
//            long totalSeconds = ChronoUnit.SECONDS.between(start, end);
//            Random random = new Random();
//            long randomSeconds = totalSeconds > 0 ? random.nextInt((int) totalSeconds) : 0;
//            LocalDateTime randomTime = start.plusSeconds(randomSeconds);
//            // 定义日期时间格式化器
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//            // 将 LocalDateTime 对象格式化为字符串
//            String formattedTime = randomTime.format(formatter);
//            scCallRecord.setCheckTime(formattedTime);
//
//            // 生成随机通话时长（1 - 1800s）
//            scCallRecord.setTalkTime(RandomUtil.randomInt(1, 1800));
//
//            // 生成随机呼叫号码（11位数字）
//            //callRecord.setCallNumber(RandomUtil.randomNumbers(11));
//
//            // 生成随机设备编号（从三个区间中选择）
//            long[][] ranges = {{865102592500000L, 865102592599999L}, {860753221400000L, 860753221499999L}, {869850014700000L, 869850014799999L}};
//            //long[][] ranges = {{815114517000000L, 815114517099999L}};
//            int randomRangeIndex = RandomUtil.randomInt(0, ranges.length);
//            long[] selectedRange = ranges[randomRangeIndex];
//            scCallRecord.setTerminalId(RandomUtil.randomLong(selectedRange[0], selectedRange[1]));
//
//            // 生成随机设备名称
//            String[] deviceNames = {"lt55", "lt36", "c9","lt30"};
//            //String[] deviceNames = {"XC20"};
//            scCallRecord.setTerminalName(deviceNames[RandomUtil.randomInt(0, deviceNames.length)]);
//
//            // 生成随机设备位置
//            //String[] locations = {"沁园小学-停车场","沁园小学-校大门","沁园小学-教学楼办公室","沁园小学-教学楼教室", "沁园小学-操场", "沁园小学-艺术楼绘画室", "沁园小学-食堂", "沁园小学-图书馆"};
//            //String[] locations = {"初中部停车场","屏山县锦屏镇初级中学北门","初中部教学楼A","图书馆","行政楼", "大操场", "综合楼", "1楼食堂"};
//            //String[] locations = {"养老中心 - 花园","养老中心 - 康复理疗室","养老中心 - 餐厅","养老中心 - 休闲活动室","养老中心 - 阳光房", "养老中心 - 护理站", "养老中心 - 睡眠区"};
////            String[] locations = {"巴中市恩阳区渔溪镇中心小学"};
////            scCallRecord.setTerminalLocation(locations[RandomUtil.randomInt(0, locations.length)]);
//
//            // 设置 userid, username, stuNum,callNumber 字段
//            if (!userInfoList.isEmpty()) {
//                // 随机选择一个 UserInfo 对象
//                UserInfo userInfo = userInfoList.get(RandomUtil.randomInt(0, userInfoList.size()));
//                scCallRecord.setUserId(userInfo.getStudentId());
//                scCallRecord.setUserName(userInfo.getStudentName());
//                scCallRecord.setStuNum(userInfo.getStudentNumber());
//                scCallRecord.setCallNumber(userInfo.getPhoneNumber());
//            }
//
//
//            callRecords.add(scCallRecord);
//        }
//        for (ScCallRecord record : callRecords) {
//            callRecordMapper.insert(record);
//        }
//    }
//
//    public Page getCallRecordsPage(Page page, ScCallRecord param, String keyword) {
//        page.setOptimizeCountSql(false);
//        List<ScCallRecord> scCallRecords = callRecordMapper.getCallRecordsPage(page,param,keyword);
//        return page.setRecords(scCallRecords);
//    }
//
//    public void xykRecordsData(Integer numRecords,String appId,String ecCode,String schoolName) {
//        List<XykRecord> Records = new ArrayList<>();
//        // 从另一个数据库获取 studentId, studentName, studentNumber,phoneNumber 数据
//        List<UserInfo> userInfoList = getUserInfoFromAnotherDatabase(numRecords);
//        for (int i = 0; i < numRecords; i++) {
//            XykRecord xykRecord= new XykRecord();
//
//            //校园卡接口用
//            //固定的数据
//            xykRecord.setAppId(appId);
//            xykRecord.setAppType("app");
//            xykRecord.setEcCode(ecCode);
//            xykRecord.setSchoolName(schoolName);
//            xykRecord.setAuthenticity("campus_card_records");
//             //生成随机卡号
//            long[][] ranges = {{260523519600000L, 260523519699999L}};
//            int randomRangeIndex = RandomUtil.randomInt(0, ranges.length);
//            long[] selectedRange = ranges[randomRangeIndex];
//            xykRecord.setCardNumber(RandomUtil.randomLong(selectedRange[0], selectedRange[1]));
//
//             //生成随机卡类型
//            String[] deviceNames = {"XC20"};
//            xykRecord.setCardType(deviceNames[RandomUtil.randomInt(0, deviceNames.length)]);
//
//            // 生成随机绑定时间（最近一年内）
//            LocalDateTime start = LocalDateTime.now().minusWeeks(30);
//            LocalDateTime end = LocalDateTime.now();
//            long totalSeconds = ChronoUnit.SECONDS.between(start, end);
//            Random random = new Random();
//            long randomSeconds = totalSeconds > 0 ? random.nextInt((int) totalSeconds) : 0;
//            LocalDateTime randomTime = start.plusSeconds(randomSeconds);
//            // 定义日期时间格式化器
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//            // 将 LocalDateTime 对象格式化为字符串
//            String formattedTime = randomTime.format(formatter);
//            xykRecord.setBindTime(formattedTime);
//
//
//            // 设置 userid, username, stuNum,callNumber 字段
//            if (!userInfoList.isEmpty()) {
//                // 随机选择一个 UserInfo 对象
//                UserInfo userInfo = userInfoList.get(RandomUtil.randomInt(0, userInfoList.size()));
//                xykRecord.setUserId(userInfo.getStudentId());
//                //xykRecord.setUserName(userInfo.getStudentName());
//                xykRecord.setStuNum(userInfo.getStudentNumber());
//                //xykRecord.setCallNumber(userInfo.getPhoneNumber());
//            }
//
//
//            Records.add(xykRecord);
//        }
//        for (XykRecord record : Records) {
//            xykRecordMapper.insert(record);
//        }
//    }
//
//    public Page getXykRecordsPage(Page page, XykRecord param, String keyword) {
//        page.setOptimizeCountSql(false);
//        List<XykRecord> xykRecords = xykRecordMapper.getXykRecordsPage(page,param,keyword);
//        return page.setRecords(xykRecords);
//    }
//
//    public void attendanceRecordsData(Integer numRecords,String appId,String ecCode,String terminalLocation) {
//        List<AttendanceRecord> Records = new ArrayList<>();
//        // 从另一个数据库获取 studentId, studentName, studentNumber,phoneNumber 数据
//        List<UserInfo> userInfoList = getUserInfoFromAnotherDatabase(numRecords);
//        for (int i = 0; i < numRecords; i++) {
//            AttendanceRecord attendanceRecord= new AttendanceRecord();
//
////           考勤类接口用
//            attendanceRecord.setAppId(appId);
//            attendanceRecord.setUserType("STUDENT");
//            attendanceRecord.setEcCode(ecCode);
//            attendanceRecord.setTerminalLocation(terminalLocation);
//            attendanceRecord.setAuthenticity("attendance_records");
////             生成随机考勤时间（最近一周内）
//            LocalDateTime start = LocalDateTime.now().minusWeeks(1);
//            LocalDateTime end = LocalDateTime.now();
//            long totalSeconds = ChronoUnit.SECONDS.between(start, end);
//            Random random = new Random();
//            long randomSeconds = totalSeconds > 0 ? random.nextInt((int) totalSeconds) : 0;
//            LocalDateTime randomTime = start.plusSeconds(randomSeconds);
//            // 定义日期时间格式化器
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//            // 将 LocalDateTime 对象格式化为字符串
//            String formattedTime = randomTime.format(formatter);
//            attendanceRecord.setCheckTime(formattedTime);
//
//
//            // 生成随机终端编号（从三个区间中选择）
//            long[][] ranges = {{865102592400000L, 865102592499999L}, {860753221400000L, 860753221499999L}, {869850014700000L, 869850014799999L}};
//            int randomRangeIndex = RandomUtil.randomInt(0, ranges.length);
//            long[] selectedRange = ranges[randomRangeIndex];
//            attendanceRecord.setTerminalId(RandomUtil.randomLong(selectedRange[0], selectedRange[1]));
//
//            // 生成随机终端名称
//            String[] deviceNames = {"lt55", "lt36", "c9","lt30"};
//            //String[] deviceNames = {"XC20"};
//            attendanceRecord.setTerminalName(deviceNames[RandomUtil.randomInt(0, deviceNames.length)]);
//
////            // 生成随机终端位置
////            String[] locations = {"**学校-食堂一楼4号销售点"};
////            attendanceRecord.setTerminalLocation(locations[RandomUtil.randomInt(0, locations.length)]);
//
//            // 生成随机终端类型
//            String[] terminalType = {"闸机"};
//            attendanceRecord.setTerminalType(terminalType[RandomUtil.randomInt(0, terminalType.length)]);
//
//
//            // 设置 userid, username, stuNum,callNumber 字段
//            if (!userInfoList.isEmpty()) {
//                // 随机选择一个 UserInfo 对象
//                UserInfo userInfo = userInfoList.get(RandomUtil.randomInt(0, userInfoList.size()));
//                attendanceRecord.setUserId(userInfo.getStudentId());
//                attendanceRecord.setUserName(userInfo.getStudentName());
//                attendanceRecord.setStuNum(userInfo.getStudentNumber());
//                //attendanceRecord.setCallNumber(userInfo.getPhoneNumber());
//            }
//
//
//            Records.add(attendanceRecord);
//        }
//        for (AttendanceRecord record : Records) {
//            attendanceRecordMapper.insert(record);
//        }
//    }
//
//    public Page getAttendanceRecordsPage(Page page, AttendanceRecord param, String keyword) {
//        page.setOptimizeCountSql(false);
//        List<AttendanceRecord> attendanceRecords = attendanceRecordMapper.getAttendanceRecordsPage(page,param,keyword);
//        return page.setRecords(attendanceRecords);
//    }
//
//    public void temperatureRecordsData(Integer numRecords,String appId,String ecCode,String terminalLocation) {
//        List<TemperatureRecord> Records = new ArrayList<>();
//        // 从另一个数据库获取 studentId, studentName, studentNumber,phoneNumber 数据
//        List<UserInfo> userInfoList = getUserInfoFromAnotherDatabase(numRecords);
//        for (int i = 0; i < numRecords; i++) {
//            TemperatureRecord temperatureRecord= new TemperatureRecord();
//
////          测温类接口用
//            temperatureRecord.setAppId(appId);
//            temperatureRecord.setUserType("STUDENT");
//            temperatureRecord.setEcCode(ecCode);
//            temperatureRecord.setTerminalLocation(terminalLocation);
////             生成随机考勤时间（最近一周内）
//            LocalDateTime start = LocalDateTime.now().minusWeeks(1);
//            LocalDateTime end = LocalDateTime.now();
//            long totalSeconds = ChronoUnit.SECONDS.between(start, end);
//            Random random = new Random();
//            long randomSeconds = totalSeconds > 0 ? random.nextInt((int) totalSeconds) : 0;
//            LocalDateTime randomTime = start.plusSeconds(randomSeconds);
//            // 定义日期时间格式化器
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//            // 将 LocalDateTime 对象格式化为字符串
//            String formattedTime = randomTime.format(formatter);
//            temperatureRecord.setCheckTime(formattedTime);
//
//
//            // 生成随机终端编号（从三个区间中选择）
//            long[][] ranges = {{865102592400000L, 865102592499999L}, {860753221400000L, 860753221499999L}, {869850014700000L, 869850014799999L}};
//            int randomRangeIndex = RandomUtil.randomInt(0, ranges.length);
//            long[] selectedRange = ranges[randomRangeIndex];
//            temperatureRecord.setTerminalId(RandomUtil.randomLong(selectedRange[0], selectedRange[1]));
//
//            // 生成随机终端名称
//            String[] deviceNames = {"lt55", "lt36", "c9","lt30"};
//            //String[] deviceNames = {"XC20"};
//            temperatureRecord.setTerminalName(deviceNames[RandomUtil.randomInt(0, deviceNames.length)]);
//
////            // 生成随机终端位置
////            String[] locations = {"**学校-食堂一楼4号销售点"};
//            temperatureRecord.setTerminalLocation(locations[RandomUtil.randomInt(0, locations.length)]);
//
//            // 生成随机体温（范围 36℃ - 38℃）
//            double minTemperature = 35.3;
//            double maxTemperature = 37.3;
//            double randomTemperature = minTemperature + (maxTemperature - minTemperature) * random.nextDouble();
//            // 限制为一位小数
//            DecimalFormat df = new DecimalFormat("#.#");
//            String formattedTemperature = df.format(randomTemperature);
//            double finalTemperature = Double.parseDouble(formattedTemperature);
//            temperatureRecord.setTemperature(finalTemperature);
//
//
//            // 设置 userid, username, stuNum,callNumber 字段
//            if (!userInfoList.isEmpty()) {
//                // 随机选择一个 UserInfo 对象
//                UserInfo userInfo = userInfoList.get(RandomUtil.randomInt(0, userInfoList.size()));
//                temperatureRecord.setUserId(userInfo.getStudentId());
//                temperatureRecord.setUserName(userInfo.getStudentName());
//                temperatureRecord.setStuNum(userInfo.getStudentNumber());
//                //attendanceRecord.setCallNumber(userInfo.getPhoneNumber());
//            }
//
//
//            Records.add(temperatureRecord);
//        }
//        for (TemperatureRecord record : Records) {
//            temperatureRecordMapper.insert(record);
//        }
//    }
//    public Page getTemperatureRecordsPage(Page page, TemperatureRecord param, String keyword) {
//        page.setOptimizeCountSql(false);
//        List<TemperatureRecord> temperatureRecords = temperatureRecordMapper.getTemperatureRecordsPage(page,param,keyword);
//        return page.setRecords(temperatureRecords);
//    }

    // 修改 getUserInfoFromAnotherDatabase 方法，根据 schoolName 获取该学校下的用户信息
    private List<StudentInfo> getUserInfoFromAnotherDatabase(String schoolName) {
        // 从 school_info 表中根据 schoolName 查询对应的 ecid
        QueryWrapper<SchoolInfo> schoolQueryWrapper = new QueryWrapper<>();
        schoolQueryWrapper.eq("school_name", schoolName);
        List<SchoolInfo> schoolInfoList = schoolMapper.selectList(schoolQueryWrapper);

        List<StudentInfo> result = new ArrayList<>();
        if (!schoolInfoList.isEmpty()) {
            String ecid = schoolInfoList.get(0).getEcid();
            // 从 student_info 表中根据 ecid 查询对应的学生信息
            QueryWrapper<StudentInfo> studentQueryWrapper = new QueryWrapper<>();
            studentQueryWrapper.eq("ec_code", ecid);
            // 直接获取该学校下的所有学生信息
            result = studentInfoMapper.selectList(studentQueryWrapper);
        }
        return result;
    }

    public void generateData(String dataType, List<String> schoolNames) {
        for (String schoolName : schoolNames) {
            // 使用 QueryWrapper 添加 schoolName 作为查询条件
            QueryWrapper<DataTypeConfig> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("school_name", schoolName);
            List<DataTypeConfig> configList = dataTypeConfigMapper.selectList(queryWrapper);
            Map<String, List<DataTypeConfig>> configMap = new HashMap<>();
            for (DataTypeConfig config : configList) {
                configMap.computeIfAbsent(config.getDataType(), k -> new ArrayList<>()).add(config);
            }

            List<GeneratedData> generatedDataList = new ArrayList<>();
            // 调用修改后的方法获取该学校的所有学生信息
            List<StudentInfo> userInfoList = getUserInfoFromAnotherDatabase(schoolName);

            Random random = new Random();
            for (StudentInfo userInfo : userInfoList) {
                int generateCount = 0;
                if ("考勤类".equals(dataType)) {
                    // 按照比例决定生成 1 条、2 条或者 3 条学生数据
                    int randomPercent = random.nextInt(100);
                    if (randomPercent < 5) {
                        generateCount = 1;
                    } else if (randomPercent < 95) {
                        generateCount = 2;
                    } else {
                        generateCount = 3;
                    }
                } else if ("话机类".equals(dataType)) {
                    int randomPercent = random.nextInt(100);
                    if (randomPercent < 80) {
                        generateCount = 0;
                    } else if (randomPercent < 95) {
                        generateCount = 1;
                    } else {
                        generateCount = 2;
                    }
                }else if ("定乾话机类".equals(dataType)) {
                    int randomPercent = random.nextInt(100);
                    if (randomPercent < 80) {
                        generateCount = 0;
                    } else if (randomPercent < 95) {
                        generateCount = 1;
                    } else {
                        generateCount = 2;
                    }
                } else if ("校园卡类".equals(dataType)) {
                    generateCount = 1;
                } else if ("测温类".equals(dataType)) {
                    int randomPercent = random.nextInt(100);
                    if (randomPercent < 10) {
                        generateCount = 0;
                    } else {
                        generateCount = 1;
                    }
                }

                for (int i = 0; i < generateCount; i++) {
                    GeneratedData generatedData = new GeneratedData();
                    generatedData.setSchoolName(schoolName);
                    generatedData.setDataType(dataType);
                    Map<String, Object> dataFields = new HashMap<>();
                    List<DataTypeConfig> fieldConfigs = configMap.get(dataType);

                    if (fieldConfigs != null) {
                        for (DataTypeConfig config : fieldConfigs) {
                            String fieldName = config.getFieldName();
                            String fieldType = config.getFieldType();
                            String fieldRule = config.getFieldRule();

                            // 传递生成的数据数量
                            Object value = generateFieldValue(fieldType, fieldRule, userInfo, generateCount, i);
                            dataFields.put(fieldName, value);
                        }
                    }
                    generatedData.setDataFields(dataFields);
                    generatedDataList.add(generatedData);
                }
            }

            // 将生成的数据保存到数据库
            for (GeneratedData data : generatedDataList) {
                generatedDataMapper.insert(data);
            }
            System.out.println("共生成：" + generatedDataList.size() + "条数据");
        }
    }

    // 修改 generateFieldValue 方法，接受一个 UserInfo 对象而不是一个列表
    private Object generateFieldValue(String fieldType, String fieldRule, StudentInfo userInfo,int generateCount,int currentIndex) {
        Random random = new Random();
        switch (fieldType) {
            case "String":
                if (fieldRule.startsWith("用户信息")) {
                    String userInfoField = fieldRule.substring("用户信息:".length());
                    if (userInfo != null) {
                        Map<String, java.util.function.Supplier<String>> fieldMap = new HashMap<>();
                        fieldMap.put("用户ID", userInfo::getStudentId);
                        fieldMap.put("ecCode", userInfo::getEcCode);
                        fieldMap.put("学生姓名", userInfo::getStudentName);
                        fieldMap.put("学号", userInfo::getStudentNumber);
                        fieldMap.put("手机号", () -> {
                            String phoneNumbers = userInfo.getPhoneNumber();
                            if (phoneNumbers != null && phoneNumbers.contains(",")) {
                                String[] phoneArray = phoneNumbers.split(",");
                                int randomIndex = random.nextInt(phoneArray.length);
                                return phoneArray[randomIndex];
                            }
                            return phoneNumbers;
                        });

                        for (Map.Entry<String, java.util.function.Supplier<String>> entry : fieldMap.entrySet()) {
                            if (entry.getKey().equals(userInfoField)) {
                                return entry.getValue().get();
                            }
                        }
                    }
                }else if (fieldRule.startsWith("地址:")) {
                    String[] parts = fieldRule.split(":");
                    if (parts.length == 3) {
                        String keyword = parts[1];
                        String city = parts[2];
                        return getRandomAddressByKeyword(keyword, city);
                    }
                }
                return fieldRule;
            case "Integer":
                if (fieldRule.contains(";")) {
                    // 处理百分比规则，例如: 70%:1-100;20%:101-1000;10%:1001-1800
                    String[] rules = fieldRule.split(";");
                    int randomPercent = random.nextInt(100) + 1;
                    int cumulativePercent = 0;
                    for (String rule : rules) {
                        String[] parts = rule.split(":");
                        int percent = Integer.parseInt(parts[0].replace("%", ""));
                        cumulativePercent += percent;
                        if (randomPercent <= cumulativePercent) {
                            String[] range = parts[1].split("-");
                            int min = Integer.parseInt(range[0]);
                            int max = Integer.parseInt(range[1]);
                            return RandomUtil.randomInt(min, max);
                        }
                    }
                } else if (fieldRule.contains("-")) {
                    String[] range = fieldRule.split("-");
                    int min = Integer.parseInt(range[0]);
                    int max = Integer.parseInt(range[1]);
                    return RandomUtil.randomInt(min, max);
                }
                return random.nextInt();
            case "Long":
                if (fieldRule.contains("-")) {
                    String[] range = fieldRule.split("-");
                    long min = Long.parseLong(range[0]);
                    long max = Long.parseLong(range[1]);
                    return RandomUtil.randomLong(min, max);
                }
                return random.nextLong();
            case "Double":
                if (fieldRule.contains("-")) {
                    String[] range = fieldRule.split("-");
                    double min = Double.parseDouble(range[0]);
                    double max = Double.parseDouble(range[1]);
                    double randomValue = min + (max - min) * random.nextDouble();
                    DecimalFormat df = new DecimalFormat("#.#");
                    return Double.parseDouble(df.format(randomValue));
                }
                return random.nextDouble();
            case "Datetime":
                if (fieldRule.contains("~")) {
                    String[] range = fieldRule.split("~");
                    LocalDateTime start = LocalDateTime.parse(range[0], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    LocalDateTime end = LocalDateTime.parse(range[1], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    long totalSeconds = ChronoUnit.SECONDS.between(start, end);
                    long randomSeconds = totalSeconds > 0 ? random.nextInt((int) totalSeconds) : 0;
                    LocalDateTime randomTime = start.plusSeconds(randomSeconds);
                    return randomTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                } else if ("最近1天".equals(fieldRule)) {
                    // 生成最近1天的随机时间
                    LocalDateTime now = LocalDateTime.now();
                    LocalDateTime oneDayAgo = now.minusDays(1);
                    long totalSecondsLastDay = ChronoUnit.SECONDS.between(oneDayAgo, now);
                    long randomSecondsLastDay = totalSecondsLastDay > 0 ? random.nextInt((int) totalSecondsLastDay) : 0;
                    LocalDateTime randomTimeLastDay = oneDayAgo.plusSeconds(randomSecondsLastDay);
                    return randomTimeLastDay.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                } else if (fieldRule.contains(";")) {
                    String[] intervals = fieldRule.split(";");
                    String selectedInterval;
                    if (generateCount == 2) {
                        // 如果是考勤类生成了两条数据，则从两个时间区间分别生成数据
                        selectedInterval = intervals[currentIndex % intervals.length];
                    } else if (generateCount == 3) {
                        if (currentIndex < 2) {
                            // 前两条数据从不同的区间生成
                            selectedInterval = intervals[currentIndex];
                        } else {
                            // 第三条数据随机选取一个区间
                            int randomIndex = random.nextInt(intervals.length);
                            selectedInterval = intervals[randomIndex];
                        }
                    } else {
                        // 如果是一条数据，则从两个区间随机选取一个区间生成数据
                        int randomIndex = random.nextInt(intervals.length);
                        selectedInterval = intervals[randomIndex];
                    }

                    String[] timeRange = selectedInterval.split("-");
                    // 指定时间格式为 HH:mm 来解析时间字符串
                    LocalTime startTime = LocalTime.parse(timeRange[0], DateTimeFormatter.ofPattern("HH:mm"));
                    LocalTime endTime = LocalTime.parse(timeRange[1], DateTimeFormatter.ofPattern("HH:mm"));
                    long totalSecondsInInterval = ChronoUnit.SECONDS.between(startTime, endTime);
                    long randomSecondsInInterval = totalSecondsInInterval > 0 ? random.nextInt((int) totalSecondsInInterval) : 0;
                    LocalTime randomTime = startTime.plusSeconds(randomSecondsInInterval);
                    LocalDate currentDate = LocalDate.now();
                    LocalDateTime randomDateTime = LocalDateTime.of(currentDate, randomTime);
                    return randomDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                }
                return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            default:
                return null;
        }
    }


    public Page queryDataByPages(Page page, GeneratedData param, String keyword) {
        page.setOptimizeCountSql(false);
        List<GeneratedData> data = generatedDataMapper.queryDataByPages(page,param,keyword);
        return page.setRecords(data);
    }

    public Page queryConfigByPages(Page page, DataTypeConfig param, String keyword) {
        page.setOptimizeCountSql(false);
        List<DataTypeConfig> data = generatedDataMapper.queryConfigByPages(page,param,keyword);
        return page.setRecords(data);
    }

    private static final String AMAP_API_URL = "https://restapi.amap.com/v3/place/text";
    private static final String AMAP_API_KEY = "47235ed632b28a30b36409ddab49d59a"; // 替换为你的高德地图 API Key

    // 调用高德地图 API 获取随机地址
    private String getRandomAddressByKeyword(String keyword, String city) {
        HttpClient httpClient = HttpClients.createDefault();
        String url = AMAP_API_URL + "?key=" + AMAP_API_KEY + "&keywords=" + keyword + "&city=" + city + "&output=json";
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                String result = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSONObject.parseObject(result);
                if ("1".equals(jsonObject.getString("status"))) {
                    JSONArray pois = jsonObject.getJSONArray("pois");
                    if (pois != null && !pois.isEmpty()) {
                        Random random = new Random();
                        int randomIndex = random.nextInt(pois.size());
                        JSONObject poi = pois.getJSONObject(randomIndex);
                        return poi.getString("address");
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}